<script>
	import {
		BASE_URL,
		SOCKET_URL
	} from '@/config/config.js';
	import {
		initData
	} from '@/config/util.js';

	export default {
		globalData: {
			currentTab: 0,
			msgNum: 0,
			nickNameChange: false,
			avatarChange: false,
			headerChange: false,
			phoneChange: false,
			inviteChange: false,	
			sexChange: false,
			areaChange: false,
			birthChange: false,
			usignChange: false,
		},
		data() {
			return {
				is_open_socket: false, //避免重复连接
				connectNum: 1, // 重连次数
				traderDetailIndex: 100, // traderDetailIndex ==2 重连
				accountStateIndex: 100, // traderDetailIndex ==1 重连
				followFlake: false, // traderDetailIndex == true 重连
				timeout: 15000, //多少秒执行检测
				heartbeatInterval: null, //检测服务器端是否还活着
				reconnectTimeOut: null //重连之后多久再次重连
			}
		},
		onLaunch: function() {
			console.log('App Launch');
			// // #ifdef APP-PLUS
			// plus.push.getClientInfoAsync(
			// 	info => {
			// 		console.log('Success', JSON.stringify(info.clientid));
			// 	},
			// 	e => {
			// 		console.log('Failed', JSON.stringify(e));
			// 	}
			// );
			// //#endif
			uni.$on('sign_in', userId => {
				console.log('监听到事件来自登陆页面登入记录，userId' + userId);
				if (userId) {
					this.connectSocket(userId);
				}
			});
			try {
				const token = uni.getStorageSync('token');
				if (token) {
					this.$store.commit('SetToken', token);
					this.getUserInfo(token)
				} else {
					// uni.reLaunch({
					// 	url: '/pages/login/login'
					// });
				}
			} catch (e) {}
			initData()
			
		},
		onShow: function() {
			console.log('App Show')

		},
		onHide: function() {
			console.log('App Hide')
		},
		onUnload() {
			uni.closeSocket();
		},
		methods: {

			getUserInfo(token) {
				uni.$u.http.get("/user/getUserInfo").then(res => {
					this.$store.commit('SetUser', res);
					this.$store.commit('SetUserId', res.userId);
					// #ifdef APP-PLUS
					this.connectSocket(res.userId);
					// #endif	
				})

			},
			connectSocket(userId) {
				if(!userId){return}
				var that = this
				var socketTask = uni.connectSocket({
					url: SOCKET_URL + `/ws/` + userId,
					header: {"Authorization": that.$store.state.token},
					success: res => {
						uni.onSocketOpen(() => {
							that.$store.commit('SetOnline', res.userId);
							console.log('WebSocket连接已打开！');
							clearInterval(that.reconnectTimeOut)
							clearInterval(that.heartbeatInterval)
							that.is_open_socket = true;
							that.start(userId)
						});
						uni.onSocketMessage(result => {
							let data = JSON.parse(result.data);
							//console.log(JSON.stringify(data));
							//console.log(data.type)
							
							if (data.type != 'ping') {
							    uni.$emit('chat_msg', result.data)
							    
								if (typeof data.msg !== 'undefined') {
									that.$store.commit('SetMessages', data.msg);
								}
								//this.$store.commit('SetUserChatList', data.userList);
								let chatUser = that.$store.state.chatUser;
								
								
								console.log(result.data)
								let toUser = JSON.parse(result.data)
								let user = uni.getStorageSync('user');
								if ((!chatUser || chatUser.userId != toUser.fromUserid) && toUser.fromUserid != toUser.toUserid) {
									uni.$emit('msgNumAdd', toUser.fromUserid)	
									let chatMsgList = that.$store.state.chatMsgList;
									chatMsgList.unshift(result.data)
									that.$store.commit('SetChatMsgList', chatMsgList);
									//推送

								}
								console.log(chatUser.userId)
								if(chatUser && chatUser.userId == toUser.fromUserid)
								{		
									uni.$u.http.get("/chat/updateUnread?toUserId="+toUser.fromUserid).then((res)=>{})
								}
								
							}

						});
						uni.onSocketError(err => {
							that.$store.commit('SetOnline', null);
							console.log("WebSocket连接发生错误！")
							console.log(this.heartbeatInterval)
														
							clearInterval(this.heartbeatInterval)
							clearInterval(this.reconnectTimeOut)
							console.log(this.heartbeatInterval)
							this.reconnect(userId);
							
							// if (this.connectNum < 6) {
							// 	uni.showToast({
							// 		title: `WebSocket连接失败，正尝试第${this.connectNum}次连接`,
							// 		icon: "none"
							// 	})
							// 	this.reconnect();
								
							// 	this.connectNum += 1
							// } else {
							// 	uni.$emit('connectError');
							// 	this.connectNum = 1
							// }
						});
						uni.onSocketClose(close => {
							this.$store.commit('SetOnline', null);
							console.log("WebSocke已关闭！")
							clearInterval(this.heartbeatInterval)
							clearInterval(this.reconnectTimeOut)
							this.is_open_socket = false;
							this.socketTask = null
							// if (this.connectNum < 6) {
							// 	console.log(userId)
							// 	this.reconnect(userId);
							// } else {
							// 	uni.$emit('connectError');
							// 	this.connectNum = 1
							//}
							this.reconnect(userId);

						});
					},
					fail: () => {
						uni.showToast({
							title: '连接失败，请检查网络',
							icon: 'none',
							duration: 2000
						});
					}
				});
				console.log(socketTask)
			}, //开启心跳检测
			start(userId) {
				let message = {
				    type: 'ping',
					toUserid: userId,
					fromUserid: userId,
					time: new Date().valueOf(),
					state: 1,
					loading: true,
					right: true,
					avatar: ''
				
				};
				this.heartbeatInterval = setInterval(() => {
					uni.sendSocketMessage({
						data: JSON.stringify(message)
					});
				}, 3000)
			},

			//重新连接
			reconnect(userid) {
				userid = this.$store.state.userId
				console.log(userid)
				//停止发送心跳
				if(userid){
					clearInterval(this.heartbeatInterval)
					//如果不是人为关闭的话，进行重连
					// if (!this.is_open_socket && (this.traderDetailIndex == 2 || this.accountStateIndex == 0 || this
					// 		.followFlake)) {
					// 	this.reconnectTimeOut = setInterval(() => {
					// 		this.connectSocket(userid);
					// 	}, 5000)
					// }
					this.reconnectTimeOut = setInterval(() => {
						this.connectSocket(userid);
					}, 5000)
				}
				
			},
			

		}
	}
</script>

<style lang="scss">
	/* 注意要写在第一行，同时给style标签加入lang="scss"属性 */
	@import "@/uni_modules/uview-ui/index.scss";
</style>
